package com.th.campusmatchbackend.controller;

import com.th.campusmatchbackend.common.BaseResponse;
import com.th.campusmatchbackend.common.ErrorCode;
import com.th.campusmatchbackend.common.ResultUtils;
import com.th.campusmatchbackend.exception.BusinessException;
import com.th.campusmatchbackend.model.domain.User;
import com.th.campusmatchbackend.model.request.QQLoginRequest;
import com.th.campusmatchbackend.service.ThirdPartyLoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.th.campusmatchbackend.contant.UserContant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/login")
@Slf4j
public class ThirdPartyLoginController {

    @Resource
    private ThirdPartyLoginService thirdPartyLoginService;


    @GetMapping("/QQ")
    public BaseResponse<String> qqLogin() throws IOException {
        String url = thirdPartyLoginService.Login();
        log.info("ThirdPartyLoginController qq#url = {}",url);
        return ResultUtils.success(url);

    }

    @PostMapping("/loginInfo")
    public BaseResponse<User> saveLoginInfo(@RequestBody QQLoginRequest qqLoginRequest, HttpServletRequest request) throws IOException {
        if (qqLoginRequest == null || StringUtils.isBlank(qqLoginRequest.getCode())) {
            throw new BusinessException(ErrorCode.NULL_LOGIN, "请重新登录");
        }
        User user = thirdPartyLoginService.getLonginInfo(qqLoginRequest, request);
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return ResultUtils.success(user);

    }


}
